<?php

namespace App\Http\Api\Controllers;

use App\Library\JsonData;
use App\Models\Attachment;
use Dcat\Admin\Traits\HasUploadedFile;
use Illuminate\Http\Request;

class AttachmentController extends Controller {
	use HasUploadedFile;
	/**
	 * 文件上传
	 * @param  $file   [文件表单名file或者_file_]
	 * @return [json]           [description]
	 */
	public function upload(Request $request) {
		$driver = env("FILESYSTEM_DRIVER", '');
		$disk = $this->disk($driver);
		$type = $request->input("type", "image");
		if ($request->hasFile('file')) {
			$file = $request->file("file");
		} else {
			$file = $request->file("_file_");
		}
		if (empty($file)) {
			return $this->responseErrorMessage("未检测到文件");
		}
		$md5 = md5_file($file);

		$model = new Attachment();
		$exist = $model->where("md5", $md5)->first();
		if (!empty($exist)) {
			return $this->responseUploaded($exist->path, $disk->url($exist->path), $exist->id);
		}
		// 获取上传的字段名称
		$pic = ['jpg', 'jpeg', 'gif', 'bmp', 'png', "ico", 'svg'];
		$dir = "file";
		if (in_array(strtolower($file->extension()), $pic)) {
			$dir = "image";
		}

		$newName = date("Ym") . "/" . $md5 . "." . $file->getClientOriginalExtension();
		try {
			$result = $disk->putFileAs($dir . "s", $file, $newName);
		} catch (\Exception $e) {
			return $this->responseErrorMessage("上传失败", $e->getMessage());
		}

		$path = $dir . "s/" . $newName;
		if ($result) {
			$attachment = new Attachment([
				'model' => $request->input("module", "default"),
				'path' => $path,
				'type' => $type,
				'name' => $file->getClientOriginalName(),
				'driver' => $driver,
				'create_at' => date("Y-m-d H:i:s"),
				'updated_at' => date("Y-m-d H:i:s"),
			]);

			$res = $attachment->save();
			if ($attachment->id) {
				return $this->responseUploaded($path, $disk->url($path), $attachment->id);
			}
		}
		return $this->responseErrorMessage('文件上传失败');
	}
	/**
	 * 上传成功
	 * @param  [type] $path [description]
	 * @param  [type] $url  [description]
	 * @return [type]       [description]
	 */
	function responseUploaded(string $path, string $url, string $id = '') {
		return json_msg(0, "上传成功", ['path' => $path, 'url' => $url, "id" => $id]);
	}
	//上传失败
	function responseErrorMessage(string $msg = "上传失败", $data = null) {
		return json_msg(500, $msg, $data);
	}
}
